var dialog;
var bandComm = false;

$(document).ready(function() {
    $('body').on('click', '#sendComment', function() {
        dialog.close();
    });

    $("#scheduler").kendoScheduler({
        toolbar: [ { name: "pdf", text: 'Exportar a PDF'} ],
        pdf: {
            allPages: true,
            fileName: "Agenda.pdf"
        },
        messages: {
            showFullDay: "Ver día completo",
            date: "Fecha",
            time: "Hora",
            event: "Curso"
        },
        date: new Date(),
        showWorkHours: true,
        workDayStart: new Date("2013/1/1 08:00 AM"),
        workDayEnd: new Date("2013/1/1 6:00 PM"),
        views: [
            {
                type: "day",
                dateHeaderTemplate: kendo.template('<strong>#=kendo.toString(date, "ddd") + " " + kendo.toString(date, "m")#</strong>')
            },
            {
                type: "workWeek",
                selected: true,
                dateHeaderTemplate: kendo.template('<strong>#=kendo.toString(date, "ddd") + " " + kendo.toString(date, "m")#</strong>')
            },
            {
                type: "week",
                dateHeaderTemplate: kendo.template('<strong>#=kendo.toString(date, "ddd") + " " + kendo.toString(date, "m")#</strong>')
            },
            "month",
            "agenda",
            { type: "timeline", eventHeight: 50 }
        ],
        timezone: "Etc/UTC",
        dataSource: {
            batch: true,
            transport: {
                read: {
                    url: appBosch.crud.read,
                    dataType: "json"
                },
                update: {
                    url: appBosch.crud.update,
                    dataType: "json"
                },
                create: {
                    url: appBosch.crud.create,
                    dataType: "json"
                },
                destroy: {
                    url: appBosch.crud.destroy,
                    dataType: "json"
                },
                parameterMap: function(options, operation) {
                    switch (operation) {
                        case "read":
                            break;
                        case "update":
                            return {models: kendo.stringify(options.models)};
                            break;
                        case "create":
                            return {models: kendo.stringify(options.models)};
                            break;
                        case "destroy":
                            return {id: options.models[0].id};
                            break;
                    }
                }
            },
            schema: {
                timezone: "Etc/UTC",
                model: {
                    id: "id",
                    fields: {
                        ownerId: { from: "user_id", defaultValue: appBosch.owner },
                        testId: { nullable: false, from: 'test_id', validation: { required: true } },
                        roomId: { nullable: false, from: 'room_id', validation: { required: true } },
                        type: { nullable: false, from: 'type', validation: { required: true } },
                        start: { type: "date", from: "start" },
                        end: { type: "date", from: "end" },
                        startTimezone: { from: "start_timezone" },
                        endTimezone: { from: "end_timezone" },
                        description: { from: "description" },
                        recurrenceId: { from: "recurrence_id" },
                        recurrenceRule: { from: "recurrence_rule" },
                        recurrenceException: { from: "recurrence_exception" },
                        isAllDay: { type: "boolean", from: "is_all_day", visible: false },
                        title: { from: 'title' }
                    }
                }
            },
            requestEnd: function (e) {
                switch (e.type) {
                    case 'update':
                        if ( e.response == false ) {
                            alert('No se puede modificar este curso porque ya tiene asociados inscritos.');
                            e.sender.read();
                        }
                        break;
                    case 'destroy':
                        if ( e.response != false ) {
                            var contentTemp = $("#windowComment").html();
                            var temp = kendo.template(contentTemp);
                            var combo;
                            dialog = $('<div id="window" ></div>');
                            dialog.html(temp({url: appBosch.urlCreateLogDestroy + '/' + e.response.id}));
                            dialog = dialog.kendoWindow({
                                title: "Comentario",
                                minWidth: 400,
                                modal: true,
                                deactivate: function () {
                                    $.get($('#sendComment').data('url'), {comment: combo.text() + ' - ' + $('#comment').val()}, function (resp) {
                                    });
                                    this.destroy();
                                },
                                open: function () {
                                    combo = $('#comboComment').kendoDropDownList({
                                        dataTextField: "text",
                                        dataValueField: "value",
                                        dataSource: {
                                            data: [
                                                { value: 1, text: 'Falta de instructor' },
                                                { value: 2, text: 'Falta de sala' },
                                                { value: 3, text: 'Cupo mínimo no cumplido' },
                                                {value: 0, text: 'Otro'}
                                            ]
                                        },
                                        cascade: function () {
                                            if (this.value() == 0) {
                                                bandComm = true;
                                            } else {
                                                bandComm = false;
                                                $('comment').removeClass('req');
                                            }
                                        }
                                    }).data('kendoDropDownList');
                                },
                                close: function (e) {
                                    if (bandComm && $('#comment').val() == '') {
                                        $('#comment').addClass('req');
                                        e.preventDefault();
                                    }
                                }
                            }).data("kendoWindow").open().center();
                        } else {
                            alert('No se puede modificar este curso porque ya tiene asociados inscritos.');
                            e.sender.read();
                        }
                        break;
                }
            }
        },
        resources: [
            {
                field: "testId",
                dataTextField: "text",
                dataValueField: "value",
                dataValueColor: "color",
                dataSource: {
                    batch: true,
                    transport: {
                        read: {
                            url: appBosch.urlTests,
                            dataType: "json"
                        }
                    }
                },
                title: "Curso"
            },
            {
                field: "roomId",
                dataTextField: "text",
                dataValueField: "value",
                dataSource: {
                    batch: true,
                    transport: {
                        read: {
                            url: appBosch.urlRooms,
                            dataType: "json"
                        }
                    }
                },
                title: "Sala"
            },
            {
                field: "type",
                dataTextField: "text",
                dataValueField: "value",
                dataSource: {
                    data: [
                        { value: 1, text: "Antes del curso" },
                        { value: 2, text: "Despues del curso" }
                    ]
                },
                title: "Servicio de transporte"
            }
        ]
    });
});